import random
import time

from rest_framework.views import APIView
from rest_framework.response import Response

from app01.models import Banner
from utils.common_logger import logger  # 这个只是编辑器报错，但是实际代码没有错


class LoggerView(APIView):
    def get(self, request):
        # 以后在项目中 不能出现 print，统一都用日志 --》logger.info
        # 好处是可以通过日志级别 来控制输出的内容
        # 写个 info 级别的日志
        logger.info('info级别的日志')
        logger.error('程序崩了')
        return Response('logger')


class ExceptionView(APIView):
    def get(self, request):
        # 1 直接抛错误
        # raise Exception('主动报错')
        # raise APIException('APIException错误')

        # l=[0,1,2]
        # print(l[4])

        return Response('logger')


from utils.common_reponse import APIResponse


class ResponseView(APIView):
    def get(self, request):
        # return APIResponse(code=100)
        # return APIResponse(code=101, msg='成功')
        # return APIResponse(msg='OK')
        return APIResponse(token='asddffs.dffaiuosfo.sjgdfksjdfb', headers={'content-type': 'application/json'})


from django.http import HttpResponse


##### 测试 简单和非简单 #####
def demo_cors(request):
    print('请求方式是:', request.method)
    print('开始请求')
    res = HttpResponse('ok')

    # # 先处理简单请求，在响应头中加允许
    # res['Access-Control-Allow-Origin'] = '*'  # 允许所有前端发的请求
    #
    # # 处理非简单请求
    # if request.method == 'OPTIONS':
    #     res['Access-Control-Allow-Headers'] = '*'
    #     res['Access-Control-Allow-Methods'] = '*'

    return res


########### 测试 redis的使用 ###########
from utils.pool import POOL
from redis import Redis


def demo_redis(request):
    # conn = Redis(connection_pool=POOL, decode_responses=True)
    # conn.set('hobby', '唱跳rap篮球')  # 设置字符串
    # conn.close()

    # 统计接口访问次数
    conn = Redis(connection_pool=POOL, decode_responses=True)
    conn.incrby('count')
    count = conn.get('count')
    return HttpResponse('这是第%s次访问' % count)


from django_redis import get_redis_connection


def demo_django_redis(request):
    # 统计接口访问次数
    conn = get_redis_connection()
    conn.incrby('count')
    count = conn.get('count')
    return HttpResponse('这是第%s次访问' % count)


from django.core.cache import cache


class Person:
    pass


# django的缓存
def demo_cache(request):
    # # 统计接口访问次数
    count = (cache.get('new_count') or 0) + 1
    cache.set('new_count', count)

    # person = Person()
    # person.name = 'chosen'
    # person.age = 20
    # cache.set('person', person)

    res = cache.get('person')
    print(res.age)

    return HttpResponse('这是第%s次访问' % count)


############### 测试celery异步 ###############
# from celery_task.user_task import send_sms
#
#
# def demo_celery(request):
#     res = send_sms.delay('15990065683')  # 会得到id号---》会提交到broker中
#     return HttpResponse(res)


######### 第三方方案 #########
from .task import send_email


def demo_celery(request):
    res = send_email.delay('123@qq.com')
    return HttpResponse(res)


################### 轮播图接口 ###################
from rest_framework.viewsets import GenericViewSet
from utils.common_view import CommonListModelMixin, CacheListModelMixin
from .serializer import BannerSerializer
from .models import Banner
from django.core.cache import cache
from utils.common_logger import logger


class BannerView(GenericViewSet, CacheListModelMixin):
    serializer_class = BannerSerializer
    queryset = Banner.objects.all().filter(is_delete=False, is_show=True).order_by('orders')
    cache_key = 'cache_banner_list'

    # # 重写list
    # def list(self, request, *args, **kwargs):
    #     # 1 先从缓存拿
    #     banner_list = cache.get('cache_banner_list')
    #     # 2 拿不到再去数据库里拿数据
    #     if not banner_list:
    #         logger.info('去数据库取数据了...')
    #         res = super().list(request, *args, **kwargs)
    #         # 3 放到缓存
    #         banner_list = res.data.get('results')
    #         cache.set('cache_banner_list', banner_list)  # 列表套字典
    #     return APIResponse(results=banner_list)


################### 同步秒杀接口 ###################
# from rest_framework.viewsets import ViewSet
# from rest_framework.decorators import action
#
#
# class SeckillView(ViewSet):
#     @action(methods=['POST'], detail=False)
#     def seckill(self, request, *args, **kwargs):
#         # 1 取出传入的课程id   1s
#         course_id = request.data.get('course_id')
#         time.sleep(1)
#         # 2 查询课程是否还有剩余  1s
#         print('根据课程id：%s，查询课程是否还有剩余，耗时1s' % course_id)
#         res = random.choice([True, False])
#         if res:  # 模拟如果有库存
#             print('扣减库存，耗时1s')
#             time.sleep(1)
#             print('下单，生成订单，耗时1s')
#             time.sleep(1)
#             return APIResponse(msg='恭喜抢票成功')
#         else:
#             return APIResponse(msg='库存不足抢票失败')


################### 异步秒杀接口 ###################
from rest_framework.viewsets import ViewSet
from rest_framework.decorators import action
from .task import seckill
from celery.result import AsyncResult
from src import celery_app


class SeckillView(ViewSet):
    @action(methods=['POST'], detail=False)
    def seckill(self, request, *args, **kwargs):
        course_id = request.data.get('course_id')
        task_id = seckill.delay(course_id)
        return APIResponse(msg='正在排队中...', task_id=str(task_id))

    @action(methods=['POST'], detail=False, url_path='result')
    def get_result(self, request, *args, **kwargs):
        task_id = request.data.get('task_id')
        a = AsyncResult(id=task_id, app=celery_app)
        if a.successful():
            result = a.get()  # True 和 False
            if result:
                return APIResponse(success='1', msg='秒杀成功')
            else:
                return APIResponse(success='0', msg='秒杀失败')
        elif a.status == 'PENDING':
            return APIResponse(success='2', msg='任务等待被执行')
        else:
            return APIResponse(success='3', msg='秒杀任务正在执行')
